/**
 *
 * @class 表单的域
 */
zxt.ui.Field = function(name, title, type, interactor){
	this._name = name;
	this._title = title || name;
	this._type = type || "label";	
	this._interactor = interactor || InteractorManager.getInteractorFactory(this._type).getInstance();
};


/**
 * [GETTER | SETTER] 表单域的名称
 * @type string
 * @function
 */
zxt.ui.Field.prototype.name = function(v){
  if (v === undefined) {	return this._name;	}
  this._name = v;
};

/**
 * [GETTER | SETTER] 表单域的标题
 * @type string
 * @function
 */
zxt.ui.Field.prototype.title = function(v){
  if (v === undefined) {	return this._title;	}
  this._title = v;
};

/**
 * [GETTER | SETTER] 表单域的类型
 * @type string
 * @function
 */
zxt.ui.Field.prototype.type = function(v){
  if (v === undefined) {	return this._type;	}
  this._type = v;
};

/**
 * [GETTER | SETTER] 表单域的交互控件
 *
 * @type Interactor
 * @function
 */
zxt.ui.Field.prototype.interactor = function(v){
  if (v === undefined) {	return this._interactor;	}
  this._interactor = v;
};

/**
 *
 * @class 基本表单类
 */
zxt.ui.Form = function() {
	zxt.ui.Record.call(this);

	this.title = "DATA";
	this.colWidth = null;
	this.colHeight = "18px";	

	this.layout = null;
	
	this.jqSkeleton = null;
	this.jqDom = $("<div style=\"position: relative;\"/>");
	
	this._fields = [];
	this._rebuild = true;
};

/**
 * <p>
 * 根据传入的DOM元素, 解析传入的相关属性, 创建相应的区域
 * </p>
 * @function
 * @static
 * @param {DOM} elem 传入的DOM元素
 * @return {zxt.ui.Form} 创建的日期控件对象
 */
zxt.ui.Form.parse = function(elem){
	var j = $(elem);
	
	var _instance = new zxt.ui.Form();
	_instance.setValue({});

	$("div", j ).each( function( idx, dom )	{
		var _comp = $(dom).attr("zxt");
		var conf = {
			name:$(dom).attr("zxt.name"),
			title:$(dom).attr("zxt.title"),
			type:$(dom).attr("zxt.type")
		};	
		_instance.addField(conf);
		//var component = eval(_type+".parse(_dom);");
		//component.setParent(_instance);
		//var _field = new zxt.ui.Field(_name, _title, _type, component);
		//_instance._addField(_field);
	});
	return _instance;
};


zxt.defineClazz(zxt.ui.Form, zxt.ui.Record);
/**
 * 获取控件类型
 *
 * @function
 * @returns {string} "form"
 */
zxt.ui.Form.prototype.getType = function(){
	return "zxt.ui.Form";
};




/**

 * 表单添加容器
 * @private
 * @function
 * 
 */
zxt.ui.Form.prototype._addField = function( field, pos ){
	if ( zxt.util.notValue(pos) ){
		this._fields.push(field);
	} else {
		this._fields.splice(pos, 0, field);
	}
	
	var _int = field.interactor();
	this.addChild(_int);
	this.mapInteractor(field.name(), _int);
	this._rebuild = true;	
};	

/**
 * 根据传入的配置参数增加表单域
 *
 * @function
 * @param {map} conf 新增表单域的配置
 * @param {string} conf.name 表单域的名称
 * @param {string} conf.title 表单域的标题
 * @param {string} conf.type 表单域的类型
 * @param {Interactor} conf.render 表单域的交互控件
 */
zxt.ui.Form.prototype.addField = function( conf ){
	var interactor = null;
	if( zxt.util.isValue(conf.interactor) ){
		interactor = conf.interactor;
	} else {
		interactor = InteractorManager.getInteractorFactory(conf.type).getInstance();
	};
	interactor.setParent(this);
	var _field = new zxt.ui.Field(conf.name, conf.title, conf.type, interactor);		
	this._addField(_field);
	
};

/**
 * 表单的渲染函数
 *
 * @function
 * @return {DOM} 渲染成的DOM节点
 */
zxt.ui.Form.prototype.renderSelf = function(){
  if ( this.jqSkeleton == null || this._rebuild ){
		this.jqDom.empty();
		this._layInteractors();
		this._rebuild = false;
  }
	this._renderInteractors();
	this.jqDom.append( this.jqSkeleton );
	return this.jqDom.get(0);
};

/**
 * 设置表单的布局
 *
 * @function
 * @return {string|DOM} 布局DOM节点
 */
zxt.ui.Form.prototype.setLayout = function(l){
	if ( typeof l == "string" ){
		this.layout = $("#" + l);
		if ( this.layout.length == 0 ){
			throw new Error("Can NOT load Element with ID " + l);
		}		
	} else {
		this.layout = l;
	};
};

/**
 * 加载表单里面的控件
 * @private
 * @function
 */
zxt.ui.Form.prototype._layInteractors = function(){
	if ( this.layout != null ) {
		this.jqSkeleton  = this._layWithLayout();
	} else {
		this.jqSkeleton  = this._layWithoutLayout();
	}
};

/**
 * 加载表单里面的控件（有设置外层的情况）
 * @private
 * @function
 */
zxt.ui.Form.prototype._layWithLayout = function() {  
	var jqLayout = this.layout;
	for( var field in this._interactors ){
		var fInt = this._interactors[field];
		var widgetPath = "div[field="+ field +"]";
		var conts = $(widgetPath, jqLayout);
		var length = conts.length;
		if ( conts.length > 0 ){
			conts.eq(0).empty();
			conts.append( fInt.render() );
		}
	}
  return jqLayout;
};

/**
 * 加载表单里面的控件（没有设置外层的情况）
 * @private
 * @function
 */
zxt.ui.Form.prototype._layWithoutLayout = function(){
	var jqSkeleton = $("<table class=\"zxt-DataForm\" style=\"width:100%; position: relative;\" cellspacing=0 cellpadding=0 />");	
	var jqDataHeader = $("<tr class=\"zxt-FormHeader\"/>");	
	jqSkeleton.append(jqDataHeader);	
	var jqDataBody = $("<tbody/>");	
	jqSkeleton.append(jqDataBody);
	this._layHeader(jqDataHeader);    
	this._layTBody(jqDataBody);
	return jqSkeleton;
};

/**
 * 加载表单头方法
 * @private
 * @function
 */
zxt.ui.Form.prototype._layHeader = function(jqDataHeader){   
	var jqFieldTh = $("<th align=\"center\" style=\"overflow:hidden;white-space:nowrap;height:"+this.colHeight+";\"/>");
	var jqFieldDiv = $("<div class=\"containerFooter\" align=\"center\" style=\"overflow:hidden;white-space:nowrap;height:"+this.colHeight+";\">"+  "属性" +"</div>");
	jqFieldTh.append(jqFieldDiv);
	var jqTitleCell = $("<th align=\"center\" style=\"overflow:hidden;white-space:nowrap;height:"+this.colHeight+";\"/>");
	var div = $("<div class=\"containerFooter\" align=\"center\" style=\"overflow:hidden;white-space:nowrap;height:"+this.colHeight+";\">"+ "值" +"</div>");
	jqTitleCell.append(div);  
	jqDataHeader.append( jqFieldTh );
	jqDataHeader.append( jqTitleCell );
}; 

/**
 * 加载表单体方法
 * @private
 * @function
 */
zxt.ui.Form.prototype._layTBody = function(jqDataBody) {
	
	for( var i=0; i<this._fields.length; i++ ){
		var _field = this._fields[i];	
		var fInt = _field.interactor();
		var cur_row = $("<tr class=\"zxt-FormBody\"/>");	  	  
		var cur_field = $("<th align=\"center\" nowrap style=\"width:120px;\"/>");	  
		cur_field.append(this._renderContent(_field.title()));
		cur_row.append(cur_field);
		var cur_content = $("<td align=\"left\" style=\"width:100%;\"/>");	  
		cur_content.append(fInt.render());
		cur_row.append(cur_content);
		jqDataBody.append( cur_row );
	}
};	

/**
 * 加载表单内容容器的方法
 * @private
 * @function
 */
zxt.ui.Form.prototype._renderContent = function( pContent){		
	var div = $("<div style=\"overflow:hidden;white-space:nowrap;width:95%;height:"+this.colHeight+";\">"+pContent+"</div>");
	return div;
};


/**
 * 数据表单支持和数据模型的绑定
 *
 * @class 数据表单类
 * @param {zxt.data.*} m 表单数据源
 * @param {Boolean} a 是否自动绘制全部后台数据
 * @extends zxt.ui.Form
 */
zxt.ui.DataForm = function(m, a) {
	zxt.ui.Form.call(this);

	this._mode = zxt.type.Mode.VIEW;
	
	this._model = m;
	this._model.addListener(this);
	this._autodraw = a;
	
	this._index = -1;
	this._target = {};
	
	this._initialize();
	
	this._optButtons = [];
	this._operations = ["create", "edit", "delete"];
};

/**
 * 根据传入的DOM元素, 解析传入的相关属性, 创建相应的表单
 *
 * @function
 * @static
 * @param {DOM} elem 解析的DOM元素
 * @param {string} zxt.model 表单数据源
 * @param {string} zxt.layout 
 * @return {zxt.ui.DataForm} 根据传入的DOM元素创建的表单
 */
zxt.ui.DataForm.parse = function(elem){
	var j = $(elem);
	
	var _modelStr = j.attr("zxt.model");
	var _model = window[_modelStr];
	
	var _instance = new zxt.ui.DataForm(_model, true);	
	
	var _layoutStr = j.attr("zxt.layout");
	if ( zxt.util.isAvailable(_layoutStr) ){
		_instance.setLayout(_layoutStr);
	};	
	
	return _instance;
};


zxt.defineClazz(zxt.ui.DataForm, zxt.ui.Form);
/**
 * 返回控件的类型
 *
 * @function
 * @return {String} zxt.ui.DataForm
 */
zxt.ui.DataForm.prototype.getType = function(){
  return "zxt.ui.DataForm";
};


/**
 * 设置默认值
 * @function
 * @param {String} v 默认值
 */
zxt.ui.DataForm.prototype.setValue = function(v){
	this.val(v);
	this._target = this.val();
};


/**
 * 添加按钮
 * @function
 * @param {zxt.ui.Button} optButton 操作按钮
 */
zxt.ui.DataForm.prototype.addAttachButton = function(optButton){
	this._optButtons.push(optButton);
	optButton.enable(false);	
	for( var i=0; i<this._operations.length; i++ ){
		if ( this._operations[i] == optButton.operation() ){
			optButton.enable(true);
		}	
	}
};	


/**
 * [GETTER | SETTER] 
 * @type zxt.type.Mode.* 显示类型 

 * @function
 */
zxt.ui.DataForm.prototype.mode = function(v){
	if (v === undefined) {	return this._mode;	}
  this._mode = v;
    
  for( var i in this._interactors ){
		var _inter = this._interactors[i];
		_inter.onMessage( new zxt.core.Message( zxt.core.MESSAGETYPE.WM_MODE_CHANGE, {mode: this._mode} ) );
	}
};	


/**
 * DataForm初始化方法
 * @function
 * @private
 */
zxt.ui.DataForm.prototype._initialize = function(){
	
	if ( this._autodraw ){		
		var modCols = this._model.getColumns();
		for(var i=0; i<modCols.length;i++){
			var _modCol = modCols[i];	
			var _fac = null;		
			
			var _int = new zxt.ui.ColumnInteractor(_modCol);	
			_int.conf(_modCol.conf());
			this.addChild(_int);
					
			var _field = new zxt.ui.Field(_modCol.name(), _modCol.title(), _modCol.type(), _int);
			this._addField(_field);
		}
	}	
	this.setValue({});	
	
};		


/**
 * 跳转到某条数据
 *
 * @function
 * @param {number} offset 数据序号
 */
zxt.ui.DataForm.prototype.scrollTo = function(offset){
  this._index = offset;
  var _val = {};
  if ( offset >= 0 ){  
  	var _arr = this._model.get(offset, 1);
  	if ( _arr.length ==0 ){
  		alert("NO DATA");  
  		_val = {};
  	} else {
  		_val = _arr[0];
  	};  		
  }  
	this.setValue(_val);
	this._target = _val;
	this.render();
};


/**
 * 数据发生更新时通知各个控件
 *
 * @function
 * @param {zxt.data.TableModelEvents.*} e 数据更新消息
 * @param {string} param 数据值
 */
zxt.ui.DataForm.prototype.accept = function(e, param){
	
	if ( e === zxt.data.TableModelEvents.PRM ){
		this.scrollTo(this._index);
		return;
	}
	
	var _nowVal = this.getValue();		
	if ( ! this._model.equals(_nowVal, param) ){
		return;
	};	
	
	if ( e === zxt.data.TableModelEvents.DEL ){	  
		this._index = -1;
		this.render();
		return;
	}
	
	if ( e === zxt.data.TableModelEvents.UPD ){
		this.scrollTo(this._index);
		return;
	}
	
};

/**
 * DataForm点击新增方法
 * @function
 * @private
 */
zxt.ui.DataForm.prototype._onCreate = function(){
	this.setValue({});
	this.render();
		
	this.mode(zxt.type.Mode.CRET);	
	for( var i in this._optButtons ){
  	var _butt = this._optButtons[i];
  	_butt.onMessage( new zxt.core.Message( zxt.core.MESSAGETYPE.WM_OPERATION_SUPPORT, {opts: ["save", "cancel"]} ) );
  }
};

/**
 * DataForm点击编辑方法
 * @function
 * @private
 */
zxt.ui.DataForm.prototype._onEdit = function(){
	this.mode(zxt.type.Mode.EDIT);
	for( var i in this._optButtons ){
		var _butt = this._optButtons[i];
		_butt.onMessage( new zxt.core.Message( zxt.core.MESSAGETYPE.WM_OPERATION_SUPPORT, {opts: ["save", "cancel"]} ) );
	}
};

/**
 * DataForm点击删除方法
 * @function
 * @private
 */
zxt.ui.DataForm.prototype._onDelete = function(){
	
	for( var i in this._optButtons ){
		var _butt = this._optButtons[i];
		_butt.onMessage( new zxt.core.Message( zxt.core.MESSAGETYPE.WM_OPERATION_SUPPORT, {opts: ["create", "edit", "delete", "cancel"]} ) );
	}	
};	

/**
 * DataForm点击保存方法
 * @function
 * @private
 */
zxt.ui.DataForm.prototype._onSave = function(){
	var _nowVal = this.getValue();
	if (this.mode() == zxt.type.Mode.CRET){
		this._model.add(_nowVal);
	} else {	
		this._model.save(this._index, _nowVal);
	}
	
	this.setValue(_nowVal);
	this.mode(zxt.type.Mode.VIEW);
	this.render();
	
	for( var i in this._optButtons ){
		var _butt = this._optButtons[i];
		_butt.onMessage( new zxt.core.Message( zxt.core.MESSAGETYPE.WM_OPERATION_SUPPORT, {opts: ["create", "edit", "delete"]} ) );
	}	
};	

/**
 * DataForm点击取消方法
 * @function
 * @private
 */
zxt.ui.DataForm.prototype._onCancel = function(){
	this.mode(zxt.type.Mode.VIEW);	
	this.setValue(this._target);	
	this.render();
	
	for( var i in this._optButtons ){
		var _butt = this._optButtons[i];
		_butt.onMessage( new zxt.core.Message( zxt.core.MESSAGETYPE.WM_OPERATION_SUPPORT, {opts: ["create", "edit", "delete", "cancel"]} ) );
	}	
};	

/**
 * 返回表单支持的操作列表, 包括
 * <ul>
 *  <li>{@link zxt.type.Operation.CREATE} - 新增操作</li>
 *  <li>{@link zxt.type.Operation.SAVE}   - 保存操作</li>
 *  <li>{@link zxt.type.Operation.EDIT} - 编辑操作</li>
 *  <li>{@link zxt.type.Operation.DELETE} - 删除操作</li>
 *  <li>{@link zxt.type.Operation.CANCEL} - 取消操作</li>
 * </ul>
 * @function
 * @returns {string[]} 表格支持的操作列表
 */
zxt.ui.DataForm.prototype.getSupportOperations = function(){
	return [zxt.type.Operation.CREATE, zxt.type.Operation.EDIT, zxt.type.Operation.DELETE, zxt.type.Operation.SAVE, zxt.type.Operation.CANCEL ];
};	

/**
 * 响应消息的处理

 * @function
 * @param {zxt.core.Message} msg 接受到的消息
 */
zxt.ui.DataForm.prototype.onMessage = function(msg){
	var _event_type = msg.type;
	
	switch(_event_type){
		case zxt.core.MESSAGETYPE.WM_OPERATION_INVOKE:
			var _opt = msg.data.opt;
			if( _opt == zxt.type.Operation.CREATE ){
				this._onCreate();
				break;
			}
			if ( _opt == zxt.type.Operation.EDIT ){
				this._onEdit();
				break;
			}	
			
			if ( _opt == zxt.type.Operation.DELETE ){
				this._onDelete();
				break;
			}
			
			if ( _opt == zxt.type.Operation.SAVE ){
				this._onSave();
				break;
			}
			
			if ( _opt == zxt.type.Operation.CANCEL ){
				this._onCancel();
				break;
			}
			
			break;

		default:	
	};	
	
};	

/**
 * 查询表单支持和数据模型的绑定
 *

 * @class 查询表单类
 * @param {zxt.data.*} m 表单数据源
 * @param {Boolean} a 是否自动绘制全部后台数据
 * @extends zxt.ui.Form
 */
zxt.ui.SearchForm = function(m) {
	zxt.ui.Form.call(this);	
	
	this._model = m;
	
	this._optButtons = [];
	this._operations = ["query", "reset"];
};	


zxt.defineClazz(zxt.ui.SearchForm, zxt.ui.Form);
/**
 * 返回控件的类型

 *
 * @function
 * @return {String} zxt.ui.SearchForm
 */
zxt.ui.SearchForm.prototype.getType = function(){
  return "zxt.ui.SearchForm";
};


/**
 * 添加按钮
 * @function
 * @param {zxt.ui.Button} optButton 操作按钮
 */
zxt.ui.SearchForm.prototype.addAttachButton = function(optButton){
	this._optButtons.push(optButton);
	optButton.enable(false);	
	for( var i=0; i<this._operations.length; i++ ){
		if ( this._operations[i] == optButton.operation() ){
			optButton.enable(true);
		}	
	}
};

/**
 * SearchForm点击查询方法
 * @function
 * @private
 */
zxt.ui.SearchForm.prototype._onQuery = function(){
	
	var param = this.getValue();
	this._model.setParam(param);
	
	for( var i in this._optButtons ){
		var _butt = this._optButtons[i];
		_butt.onMessage( new zxt.core.Message( zxt.core.MESSAGETYPE.WM_OPERATION_SUPPORT, {opts: ["query", "reset"]} ) );
	}
};

/**
 * SearchForm点击重置方法
 * @function
 * @private
 */
zxt.ui.SearchForm.prototype._onReset = function(){
	
	for( var i in this._interactors ){
			var _inter = this._interactors[i];
			_inter.setValue("");
			_inter.render();
	}
	
	for( var i in this._optButtons ){
		var _butt = this._optButtons[i];
		_butt.onMessage( new zxt.core.Message( zxt.core.MESSAGETYPE.WM_OPERATION_SUPPORT, {opts: ["query", "reset"]} ) );
	}	
};


/**
 * 返回表单支持的操作列表, 包括

 * <ul>
 *  <li>{@link zxt.type.Operation.QUERY} - 查询操作</li>
 *  <li>{@link zxt.type.Operation.RESET} - 复原操作</li>
 * </ul>
 * @function

 * @returns {string[]} 表格支持的操作列表
 */
zxt.ui.SearchForm.prototype.getSupportOperations = function(){
	return [zxt.type.Operation.QUERY, zxt.type.Operation.RESET];
};	


/**
 * 响应消息的处理


 * @function
 * @param {zxt.core.Message} msg 接受到的消息
 */
zxt.ui.SearchForm.prototype.onMessage = function(msg){
	var _event_type = msg.type;
	
	switch(_event_type){
		case zxt.core.MESSAGETYPE.WM_OPERATION_INVOKE:
			var _opt = msg.data.opt;
			if( _opt == zxt.type.Operation.QUERY ){
				this._onQuery();
				break;
			}
			if ( _opt == zxt.type.Operation.RESET ){
				this._onReset();
				break;
			}	
			break;
		
		default:	
	};	
	
};		


